package com.tjtt.tdm.system.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.tjtt.tdm.base.BaseAction;
import com.tjtt.tdm.base.PageResult;
import com.tjtt.tdm.base.StaticDataCache;
import com.tjtt.tdm.exception.ServiceException;
import com.tjtt.tdm.system.bean.Menu;
import com.tjtt.tdm.system.bean.Opratingbutton;
import com.tjtt.tdm.system.bean.Role;
import com.tjtt.tdm.system.bean.Users;
import com.tjtt.tdm.system.service.FineGrainedAuthorityService;
import com.tjtt.tdm.system.service.LogService;
import com.tjtt.tdm.system.service.MenuService;
import com.tjtt.tdm.system.service.PipeService;
import com.tjtt.tdm.system.service.UserService;

/**
 * 菜单管理
 * @author ljy
 */
public class PipeAction extends BaseAction {
	private static final long serialVersionUID = 1L;
	private static final Log log = LogFactory.getLog(PipeAction.class); 
	private Menu menu;
	private PipeService menuService;
	private LogService logService;
	private FineGrainedAuthorityService fgaService;
	private UserService userService;
	
	private Long parentId;
	private Long menuId;
	public Long getMenuId() {
		return menuId;
	}
	public void setMenuId(Long menuId) {
		this.menuId = menuId;
	}
	public Long getParentId() {
		return parentId;
	}
	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}
	public void setMenuService(PipeService menuService) {
		this.menuService = menuService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	public void queryMenuTreeExec() {
		try {
			String returnStr = menuService.queryMenuTree();
			getResponse().setContentType("text/json; charset=utf-8");
			PrintWriter out = getResponse().getWriter();
			out.print("["+returnStr+"]");
		} catch (Exception e) {
			e.printStackTrace(); 
		}
	}
	
	public void queryMenuTreeClose() {
		try {
			String returnStr = menuService.queryMenuTreeClose();
			getResponse().setContentType("text/json; charset=utf-8");
			PrintWriter out = getResponse().getWriter();
			out.print("["+returnStr+"]");
		} catch (Exception e) {
			e.printStackTrace(); 
		}
	}
	
	public void queryMenuButton(){
		try {
			String munuId = getRequest().getParameter("menuId");
			String returnStr = menuService.queryMenuButton(munuId);
			getResponse().setContentType("text/json; charset=utf-8");
			PrintWriter out = getResponse().getWriter();
			out.print(returnStr);
		} catch (Exception e) {
			e.printStackTrace(); 
		}
	}
	public void saveMenu() throws Exception{
		setContentTypeHtml();
		PrintWriter out = getResponse().getWriter();
		try {
			Long fatherModuleId = Long.parseLong(getRequest().getParameter("fatherModuleId"));
			String menuname = getRequest().getParameter("menuname");
			String url = getRequest().getParameter("url");
			String menudesc = getRequest().getParameter("menudesc");
			Menu menu = new Menu();
			menu.setMenudesc(menudesc);
			menu.setUrl(url);
			menu.setMenuname(menuname);
			menu.setParentid(fatherModuleId);
			String id = menuService.saveMenu(menu);
			out.print("{\"result\":\"success\",\"id\":\""+id+"\",\"menuname\":\""+menuname+"\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	public void gotoUpdate() throws Exception{
		//这句话的意思，是让浏览器用utf8来解析返回的数据
		getResponse().setHeader("Content-type", "text/html;charset=UTF-8");
		//这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
		getResponse().setCharacterEncoding("UTF-8");
		PrintWriter out = getResponse().getWriter();
		try
		{
			String menuId = getRequest().getParameter("menuId");
			Menu menu = menuService.getMenuById(Long.parseLong(menuId));
			String data = "{\"id\":\""+menu.getMenuid()+"\"," +
					   "\"menuname\":\""+menu.getMenuname()+"\"," +
					   "\"url\":\""+menu.getUrl()+"\"," +
					   "\"menudesc\":\""+menu.getMenudesc()+"\"}";
			out.print(data.replaceAll("null", ""));
		}catch (Exception e)
		{
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	public void edit()  throws Exception {
		setContentTypeHtml();
		PrintWriter out = getResponse().getWriter();
		try {
			Long menuId = Long.valueOf(getRequest().getParameter("id"));
			String menuname = getRequest().getParameter("menuname");
			String url = getRequest().getParameter("url");
			String menudesc = getRequest().getParameter("menudesc");
			Menu menu = menuService.getMenuById(menuId);
			menu.setMenudesc(menudesc);
			menu.setUrl(url);
			menu.setMenuname(menuname);
			menuService.updateMenu(menu);
			out.print("{\"result\":\"update\",\"menuname\":\""+menuname+"\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	public void delete() throws Exception {
		PrintWriter out = getResponse().getWriter();
		try {
			Long menuId = Long.valueOf(getRequest().getParameter("menuId"));
			menuService.delMenu(menuId);
			out.print("{\"result\":\"success\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	/**
	 * 保存按钮
	 * author:lishu	 2015-2-28
	 */
	public void saveButton() throws Exception{
		PrintWriter out = getResponse().getWriter();
		try {
			String menuId = getRequest().getParameter("menuId");
			String buttonKey = getRequest().getParameter("buttonKey");
			String buttonName = getRequest().getParameter("buttonName");
			String requestUrl = getRequest().getParameter("requestUrl");
			Opratingbutton button = new Opratingbutton();
			button.setMenuid(Long.parseLong(menuId));
			button.setButtonkey(buttonKey);
			button.setButtonname(buttonName);
			button.setRequesturl(requestUrl);
			menuService.saveMenuButton(button);
			out.print("{\"result\":\"success\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	public void gotoButtonUpdate() throws Exception{
		//这句话的意思，是让浏览器用utf8来解析返回的数据
		getResponse().setHeader("Content-type", "text/html;charset=UTF-8");
		//这句话的意思，是告诉servlet用UTF-8转码，而不是用默认的ISO8859
		getResponse().setCharacterEncoding("UTF-8");
		PrintWriter out = getResponse().getWriter();
		try
		{
			String buttonId = getRequest().getParameter("buttonId");
			Opratingbutton button =menuService.getMenuButtonById(Long.parseLong(buttonId));
			String data = "{\"idbutton\":\""+button.getOpratingbuttonid()+"\"," +
					   "\"buttonKey\":\""+button.getButtonkey()+"\"," +
					   "\"buttonName\":\""+button.getButtonname()+"\"," +
					   "\"requestUrl\":\""+button.getRequesturl()+"\"}";
			out.print(data.replaceAll("null", ""));
		}catch (Exception e)
		{
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	/**
	 * 编辑模块
	 * @return String
	 * @author 王明龙

	 */
	public void editButton()  throws Exception {
		PrintWriter out = getResponse().getWriter();
		try {
			Long buttonId = Long.valueOf(getRequest().getParameter("idbutton"));
			String buttonKey = getRequest().getParameter("buttonKey");
			String buttonName = getRequest().getParameter("buttonName");
			String requestUrl = getRequest().getParameter("requestUrl");
			Opratingbutton button =menuService.getMenuButtonById(buttonId);
			button.setButtonkey(buttonKey);
			button.setButtonname(buttonName);
			button.setRequesturl(requestUrl);
			menuService.updateMenuButton(button);
			out.print("{\"result\":\"success\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}

	/**
	 * 删除模块
	 * @return String
	 * @author 王明龙

	 */
	public void deleteButton() throws Exception {
		PrintWriter out = getResponse().getWriter();
		try {
			Long buttonId = Long.valueOf(getRequest().getParameter("buttonId"));
			menuService.delMenuButton(buttonId);
			out.print("{\"result\":\"success\"}");
		}
		catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	public void onSort() throws Exception {
		PrintWriter out = getResponse().getWriter();
		try {
			String targetId = getRequest().getParameter("targetId");//目标ID
			String sourceId = getRequest().getParameter("sourceId");//原始位置
			String point = getRequest().getParameter("point");//具体操作
			Menu targetMenu = menuService.getMenuById(Long.parseLong(targetId));
			Menu sourceMenu =menuService.getMenuById(Long.parseLong(sourceId));
			int targetParentId = Integer.parseInt(targetMenu.getParentid().toString());
			int sourceParentId = Integer.parseInt(sourceMenu.getParentid().toString());
			int targetSequence = Integer.parseInt(targetMenu.getSequence().toString());
			int sourceSequence = Integer.parseInt(sourceMenu.getSequence().toString());
			if("bottom".equals(point)){//放到目标节点的下面  把seq大于target的都加1
				if(targetParentId == sourceParentId){//如果是同一目录
					if(targetSequence>sourceSequence){
						menuService.executeSQL("update sys_menu t set t.sequence=t.sequence-1 where t.parentid="+sourceMenu.getParentid()+" and t.sequence>" +sourceMenu.getSequence()+" and t.sequence<="+targetMenu.getSequence() );
						sourceMenu.setSequence(targetMenu.getSequence());
					}else{
						menuService.executeSQL("update sys_menu t set t.sequence=t.sequence+1 where t.parentid="+targetMenu.getParentid()+" and t.sequence>" +targetMenu.getSequence()+" and t.sequence<"+sourceMenu.getSequence() );
						sourceMenu.setSequence(targetMenu.getSequence()+1);
					}
				}else{
					menuService.executeSQL("update sys_menu t set t.sequence=t.sequence-1 where t.parentid="+sourceMenu.getParentid()+" and t.sequence>" +sourceMenu.getSequence());
					menuService.executeSQL("update sys_menu t set t.sequence=t.sequence+1 where t.parentid="+targetMenu.getParentid()+" and t.sequence>" +targetMenu.getSequence());
					sourceMenu.setSequence(targetMenu.getSequence()+1);
				}
				sourceMenu.setParentid(targetMenu.getParentid());
				menuService.updateMenu(sourceMenu);
			}else if("top".equals(point)){//放到目标节点的上面  
				if(targetParentId == sourceParentId){//如果是同一目录
					if(targetSequence>sourceSequence){
						menuService.executeSQL("update sys_menu t set t.sequence=t.sequence-1 where t.parentid="+sourceMenu.getParentid()+" and t.sequence>" +sourceMenu.getSequence()+" and t.sequence<"+targetMenu.getSequence() );
						sourceMenu.setSequence(targetMenu.getSequence()-1);
					}else{
						menuService.executeSQL("update sys_menu t set t.sequence=t.sequence+1 where t.parentid="+targetMenu.getParentid()+" and t.sequence>=" +targetMenu.getSequence()+" and t.sequence<"+sourceMenu.getSequence() );
						sourceMenu.setSequence(targetMenu.getSequence());
					}
				}else{
					menuService.executeSQL("update sys_menu t set t.sequence=t.sequence-1 where t.parentid="+sourceMenu.getParentid()+" and t.sequence>" +sourceMenu.getSequence());
					menuService.executeSQL("update sys_menu t set t.sequence=t.sequence+1 where t.parentid="+targetMenu.getParentid()+" and t.sequence>=" +targetMenu.getSequence());
					sourceMenu.setSequence(targetMenu.getSequence()-1);
				}
				sourceMenu.setParentid(targetMenu.getParentid());
				menuService.updateMenu(sourceMenu);
			}else if("append".equals(point)){//插入自己点
				//menuDao.executeSQL("update sys_menu t set t.sequence=t.sequence+1 where t.parentid="+targetMenu.getParentid());
				List<Menu> list = menuService.executeHql("from Menu m where m.parentid=" + targetMenu.getMenuid() + " order by m.sequence desc");
				if(list.size()>0){
					sourceMenu.setSequence(list.get(0).getSequence()+1);
				}else{
					sourceMenu.setSequence(1l);
				}
				sourceMenu.setParentid(targetMenu.getMenuid());
				menuService.updateMenu(sourceMenu);
			}
			out.print("{\"result\":\"success\"}");
		} catch (Exception e) {
			e.printStackTrace();
			out.print("{\"result\":\"error\"}");
		}
	}
	/**
	 * 功能菜单删除
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	public String delMenuExec() throws IOException, ServiceException{
		this.setContentType();
		PrintWriter out = getResponse().getWriter();
		JSONObject jsonObject = new JSONObject();
		try{
			menuService.delMenu(menuId);
			jsonObject.put("success",true);
			Long roleId=   this.getUser().getRoleId();
			StaticDataCache.refreshData(fgaService, roleId);
			out.write(jsonObject.toString());
			logService.saveLogInfo(this.getLogBase(), "系统管理", "菜单管理", "成功删除一条菜单记录!",1);
			return null;
		}catch (Exception e){
			e.printStackTrace();
			logService.saveLogInfo(this.getLogBase(), "系统管理", "菜单管理", "删除菜单失败!",1);
			return null;
		}
	} 
	
	/**
	 * 功能菜单保存
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	public String saveMenuExec() throws IOException, ServiceException{
		setContentType();
		PrintWriter out = getResponse().getWriter();
		JSONObject jsonObject = new JSONObject();
		try{
			//   判断菜单名是否重复
			if(menuService.findByProperty(menu.getMenuname()).size()>0){
				jsonObject.put("success",false);
				jsonObject.put("result", getText("menuName"));
			}else{
				menuService.saveMenu(menu);
				jsonObject.put("success",true);
			}
			Long roleId=   this.getUser().getRoleId();
			StaticDataCache.refreshData(fgaService, roleId);
			out.write(jsonObject.toString());
			logService.saveLogInfo(this.getLogBase(), "系统管理", "菜单管理", "成功添加一条菜单户记录!",1); 
			return null;
		}catch (Exception e){
			e.printStackTrace();
			logService.saveLogInfo(this.getLogBase(), "系统管理", "菜单管理", "添加菜单失败！",1);
			return null;
		}
	}
	/**
	 * 功能菜单编辑
	 * @return
	 * @throws IOException
	 * @throws ServiceException
	 */
	public String editMenuExec() throws IOException, ServiceException{
		setContentType();
		PrintWriter out = getResponse().getWriter();
		JSONObject jsonObject = new JSONObject();
		try{
			List<Menu> listMenus = menuService.findByProperty(menu.getMenuname());
			List<Long> listId = new ArrayList<Long>();
			for(Menu m:listMenus){
				if(!m.getMenuid().toString().equals(menu.getMenuid().toString())){
					listId.add(m.getMenuid());
				} 
			}
			//   判断菜单名是否重复
			if(listId.size()>=1 && !listId.contains(menu.getMenuid())){
				jsonObject.put("success",false);
				jsonObject.put("result", getText("menuName"));
			}else{
				menuService.updateMenu(menu);
				jsonObject.put("success",true);
			}
			Long roleId=   this.getUser().getRoleId();
			StaticDataCache.refreshData(fgaService, roleId);
			out.write(jsonObject.toString());
			logService.saveLogInfo(this.getLogBase(), "系统管理", "菜单管理", "成功修改一条菜单户记录！",1); 
			return null;
		}catch (Exception e){
			e.printStackTrace();
			logService.saveLogInfo(this.getLogBase(), "系统管理", "菜单管理", "修改菜单记录失败！",1);
			return null;
		}
	}
	
	/**
	 * 功能菜单查询
	 * @return json Ojbect
	 * @throws ServiceException
	 * @throws IOException
	 */
	public String searchMenuExec() throws ServiceException, IOException{
		setContentType();
		PrintWriter out = getResponse().getWriter();
		List<Menu> menuList = menuService.findMenuByParentId(parentId);
		out.write(getMenuJson(menuList));
		return null;
	}
	/**
	 * 根据角色获取功能菜单信息
	 * @return
	 * @throws ServiceException
	 * @throws IOException
	 */
	public String getMenuByRoleIdExec() throws ServiceException, IOException{
		setContentType();
		PrintWriter out = getResponse().getWriter();
		Users user = this.getUser();
		//-- 角色组 --
		StringBuffer sbf =new StringBuffer(); 
		for (Iterator<Role> it = user.getRoles().iterator(); it.hasNext();) {
			sbf.append(((Role)it.next()).getRoleid()+"").append(",");
		}
		//-- 角色组 end --
		List<Menu> menuList = menuService.findMenuByRoleId(parentId, sbf.toString().contains(",") ?sbf.substring(0,sbf.lastIndexOf(",")):sbf.toString());//user.getRoleId()
		out.write(getMenuJson(menuList));
		return null;
	}
	
	private String getMenuJson(List<Menu> menus){
		StringBuilder JSONStr = new StringBuilder();
		JSONStr.append("[");
		for (Menu menu : menus) {
			Long childrenNum = menu.getChildrennum();
			String path = getRequest().getContextPath();
			String icon = childrenNum > 0 ? "folder" : "file";
			String purl= menu.getPurl();
			String parentid = menu.getParentid() == null ? "" : menu
					.getParentid().toString();
			if(purl==null  ){
				JSONStr.append("{\"text\":\"" + menu.getMenuname()
						+ "\",\"id\":\"" + menu.getMenuid() + "\",\"menuname\":\""
						+ menu.getMenuname() + "\",\"parentid\":\"" + parentid
						+ "\",\"url\":\""+ menu.getUrl() + "\",\"des\":\"" 
						+ menu.getMenudesc() + "\",\"sequence\":\"" + menu.getSequence()
						+ "\",\"childrennum\":\"" + menu.getChildrennum()
						+"\",\"leaf\":" + (childrenNum == 0) + ",\"cls\":\""
						+ icon
						+  "\"},");
			}else{
				JSONStr.append("{\"text\":\"" + menu.getMenuname()
						+ "\",\"id\":\"" + menu.getMenuid() + "\",\"menuname\":\""
						+ menu.getMenuname() + "\",\"parentid\":\"" + parentid
						+ "\",\"url\":\""+ menu.getUrl() + "\",\"des\":\"" 
						+ menu.getMenudesc() + "\",\"sequence\":\"" + menu.getSequence()
						+ "\",\"childrennum\":\"" + menu.getChildrennum()
						+ "\",\"leaf\":" + (childrenNum == 0) + ",\"icon\":\""
						+ path+purl + "\"},");
			}
			
		}
		int hasN = JSONStr.lastIndexOf(",");
		if (hasN > 0) {
			JSONStr.deleteCharAt(JSONStr.lastIndexOf(","));
		}
		JSONStr.append("]");
		return JSONStr.toString();
	}
 
	/**
	 * 获取页面功能按钮
	 * @param request
	 * @return String
	 * @author 李数
	 * @date 2012-10-9 上午11:32:19
	 */
	public static String getRoleModulebutton(HttpServletRequest request){
		try {
			String roleid = (String)request.getSession().getAttribute("ROLE_INFO");
			String username = (String)request.getSession().getAttribute("username");
			String moduleid = request.getParameter("menuModuleId");
			if("admin".equals(username)){
				return null;
			}else{
				ApplicationContext  factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());   
				MenuService menu = (MenuService)factory.getBean("menuService");
				String buttonids = menu.getRoleModulebutton(roleid, moduleid);
				return buttonids;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public Menu getMenu() {
		return menu;
	}
	public void setMenu(Menu menu) {
		this.menu = menu;
	}
	public void setFgaService(FineGrainedAuthorityService fgaService) {
		this.fgaService = fgaService;
	}
	public void setLogService(LogService logService) {
		this.logService = logService;
	}
	
	
}
